package com.fyy.sentinel.controller;

import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.ServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author fyy
 * @Description 授权规则的实现
 * @Date 2021/7/15 10:28
 */
@RestController
public class WBController{

    @SentinelResource(value = "TestWB", blockHandler = "exHandler")
    @RequestMapping("/testWB")
    public String hello() {
        return "hello,Sentinel";
    }

    public String exHandler(BlockException e) {
        System.out.println(e.getMessage());
        return "系统繁忙！";
    }

    @PostConstruct
    public void init(){
        WebCallbackManager.setRequestOriginParser(ServletRequest::getRemoteAddr);
    }

    //定义授权规则
    @PostConstruct
    public void initWhiteRule(){
        //创建存放授权规则的集合
        List<AuthorityRule> rules = new ArrayList<>();
        //创建授权规则
        AuthorityRule rule = new AuthorityRule();
        //定义资源名
        rule.setResource("TestWB");
        //定义白名单
        rule.setLimitApp("127.0.0.1");
        //定义授权模式
        rule.setStrategy(RuleConstant.AUTHORITY_WHITE);
        //加入集合
        rules.add(rule);
        //加载授权规则
        AuthorityRuleManager.loadRules(rules);
    }

}
